<?php

namespace App\Http\Admin\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Admin\Models\Admin;
use App\Http\Admin\Models\Permission;

class PermissionService extends BaseService
{
    private $listData = [];

    public function __construct(Permission $permission)
    {
        parent::__construct($permission);
    }

    //过滤用户没有的id
    public function getUserPermissionIds(){
        $user_permission_ids = collect($_SERVER['current_user']->permissions)->pluck('id')->toArray();
        return $user_permission_ids;
    }

    public function tree($parent_id = 0,$all_permissions = [],$select_menu = 0,$is_auth = 0){
        if(!$parent_id){
            $query = $this->model;
            if($select_menu){
                $query = $query->where('is_menu',1);
            }
            if($is_auth){
                $user_permission_ids = $this->getUserPermissionIds();
                $query = $query->whereIn('id',$user_permission_ids);
            }
            $all_permissions = $query->orderBy('order','desc')->get();
        }


        $data = $all_permissions->where('parent_id',$parent_id)
            ->map(function($permission) use($all_permissions,$select_menu,$is_auth){
                $children = $all_permissions->where('parent_id',$permission['id']);
                if(count($children) == 0){
                    return $permission;
                }
                $permission['children'] = $this->tree($permission['id'],$all_permissions,$select_menu,$is_auth);

                return $permission;
            });

        return $data;

    }

    public function list($data = []){
        if(count($data) == 0){
            $data = $this->tree() ? $this->tree()->toArray() : [];
        }


        if(count($data) > 0){
            foreach ($data as $item){
                $itemData = array_only($item,['id','name','http_path','http_method','is_menu','menu_name','level','parent_id','menu_icon']);
                $this->listData[] = $itemData;
                if(!empty($item['children'])){
                    $this->list($item['children']->toArray());
                }
            }
        }
        return [
            'list' => $this->listData,
            'parent' => collect($this->listData)->where('level',1)->toArray(),
        ];
    }

    public function del($ids = []){
        if(!is_array($ids)){
            throw new InvalidRequestException('请传数组');
        }
        $f = $this->model->whereIn('parent_id',$ids)->exists();
        if($f){
            throw new InvalidRequestException('有子菜单 无法删除');
        }
        $result = $this->delModel($ids);
        return $result;
    }

    public function store($attributes = [])
    {
        $new_attributes = array_only($attributes, ['name', 'http_method','http_path'
            ,'is_menu','parent_id','menu_name','menu_icon']);
        //参数校验
        $this->getValidAttributes($attributes);

        if($new_attributes['parent_id'] == 0){
            $new_attributes['level'] = 1;
        }else{
            //找到父级level
            $level = $this->model->where('id',$new_attributes['parent_id'])->first()->level ?? 0;
            $new_attributes['level'] = $level + 1;
        }
        //修改过程
        if(!empty($attributes['id'])){
            $result = $this->model->where('id',$attributes['id'])->update($new_attributes);
            return $result;
        }

        //添加过程
        $result = $this->model->create($new_attributes);

        return $result;
    }

    public function getValidAttributes($attributes)
    {

        if (!paramExists($attributes,'name')) {
            throw new InvalidRequestException('请填写定义');
        }
        if(!paramExists($attributes,'parent_id')){
            throw new InvalidRequestException('请选择父级');
        }

        if (!empty($attributes['is_menu'])) {
            if(!paramExists($attributes,'menu_name')){
                throw new InvalidRequestException('请填写菜单名');
            }
            if(!paramExists($attributes,'menu_icon')){
                throw new InvalidRequestException('请填写菜单icon');
            }
        }

        if(!empty($attributes['id'])){
            if(paramExists($attributes,'name')){
                $exist = $this->model->where('name',$attributes['name'])
                    ->where('id','!=',$attributes['id'])->exists();
                if($exist){
                    throw new InvalidRequestException('该权限已存在');
                }
            }
        }else{
            if(paramExists($attributes,'name')) {
                $exist = $this->model->where('name', $attributes['name'])
                   ->exists();
                if ($exist) {
                    throw new InvalidRequestException('权限已存在');
                }
            }
        }

    }

}
